package com.wocai.jrt.admin.user.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.admin.common.bean.Node;
import com.wocai.jrt.admin.user.model.Resources;
import com.wocai.jrt.admin.user.service.spi.ResourcesService;

/**
 * 资源表控制器
 * @author yinlei
 * @date 2015-7-6 11:40:40
 */
@Controller
@RequestMapping("/resources")
public class ResourcesAction extends GenericAction<Resources> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ResourcesAction.class);
	
	@Inject
	private ResourcesService resourcesServiceImpl;
	
	/**
     * 跳转到资源列表页。
     * @param model 参数
     * @return 资源list逻辑页面
     */
    @RequestMapping("/list")
    public String list(Resources model) {
        return "resources/list";
    }
	
    /**
     * 查询资源，初始化列表页面
     * @param resource 参数
     * @return 查询结果
     */
    @ResponseBody
    @RequestMapping("/query")
    public Map<String, Object> query(@RequestBody Resources resource) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		List<Resources> list = resourcesServiceImpl.pagedList(resource);
    		
    		// 统计的时候，不需要分页
    		resource.setStart(null);
    		int totalRecord = resourcesServiceImpl.countBy(resource);
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("resource query success.");
    		}
    		
    		// jQuery datatable 就是这样的参数，阿西吧
    		//result.put("sEcho", resource.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("resource query error, msg=[{}]", e.getMessage());
		}
        return result;
    }
    
	/**
	 * 获得资源表List Tree，Json格式。
	 * @param model 参数
	 * @return 资源表List Tree
	 */
	@ResponseBody
	@RequestMapping("/tree")
	public Node tree(Resources model) {
		Node root = null;
		try {
			model.setDefaults(false);
			root = resourcesServiceImpl.getResourceTree(model);
		} catch (Exception e) {
			LOGGER.error("get resource tree error, errorMsg=[{}].", e.getMessage());
		}
		return root;
	}
	
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add() {
        return "resources/add";
    }
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     *///headers可以不添加，添加只是防止自己忘记
    @ResponseBody
    @RequestMapping(value = "/doAdd", headers = {"Content-Type=application/json; charset=utf-8"})
    public JsonBean doAdd(@RequestBody Resources model) {
    	JsonBean bean = new JsonBean();
    	try {
    		model.setResourceId(ObjectId.get().toString());
            int result = resourcesServiceImpl.save(model);
            
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
            } else {
                bean.setMessage(ERROR);
            }
		} catch (Exception e) {
			bean.setMessage(ERROR);
			LOGGER.error("add record error, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    
    /**
     * 编辑，获取记录详细信息
     * @param model 查询参数，携带ID
     * @return 记录详情
     */
    @ResponseBody
    @RequestMapping("/edit")
    public Resources edit(Resources model) {
    	try {
    		model = resourcesServiceImpl.get(model.getResourceId());
		} catch (Exception e) {
			LOGGER.error("get record detail error, msg=[{}].", e.getMessage());
		}
        return model;
    }
    
    /**
     * 更新资源表信息
     * @param model 要更新的资源表信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody Resources model) {
    	JsonBean bean = new JsonBean();
    	try {
    		if (StringUtils.isBlank(model.getResourceId())) {
    			bean.setMessage("params's id cannot be null.");
    			return bean;
    		}
    		int result = resourcesServiceImpl.updateById(model);
    		if (result == 1) {
    			bean.setMessage(SUCCESS);
    			bean.setCode(1);
    		} else {
    			bean.setMessage(ERROR);
    		}
		} catch (Exception e) {
			LOGGER.error("update resources error, msg=[{}].", e.getMessage());
			bean.setMessage("update resources error.");
		}
        return bean;
    }
    
    /**
     * 删除资源表信息
     * @param id 要删除的资源表ID
     */
    @ResponseBody
    @RequestMapping("/delete")
    public JsonBean delete(String id) {
    	JsonBean bean = new JsonBean();
    	try {
    		int result = resourcesServiceImpl.deleteById(id);
    		if (result == 1) {
    			bean.setMessage(SUCCESS);
    			bean.setCode(1);
    			LOGGER.info("delete record success, id=[{}].", id);
    		} else {
    			bean.setMessage(ERROR);
    		}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
    	// 空字符串转换为null
        binder.registerCustomEditor(String.class, new StringEditor());
    }
}
